//
//  ImageViewController.m
//  iGSS
//
//  Copyright 2010 Electronic Business Systems Ltd.
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//

#import "ImageViewController.h"

#import "FormattingUtilities.h"
#import "GSSCommunicator.h"

#import <MobileCoreServices/MobileCoreServices.h>

@implementation ImageViewController

@synthesize data;

@synthesize imageView;
@synthesize scrollView;

- (id)initWithFile:(GSSObject *)aFile inFolder:(GSSObject *)aFolder {
    if (self = [super initWithNibName:@"ImageViewController" bundle:nil]) {
        self.file = aFile;
        self.folder = aFolder;
    }
    return self;
}

- (void)dealloc {
    [data release];
    
    [imageView release];
    [scrollView release];
    
    [super dealloc];
}

- (void)reloadData {
    self.data = [NSData dataWithContentsOfFile:self.file.dataCachePath];
    UIImage *image = [UIImage imageWithData:self.data];
    if (!image)
        return;
    
    self.imageView.image = image;
    
    float screenWidth = [[UIScreen mainScreen] bounds].size.width;
    float minimumZoomScale = screenWidth / image.size.width;
    scrollView.minimumZoomScale = MIN(minimumZoomScale, 1);
    scrollView.maximumZoomScale = MAX(minimumZoomScale, 2);
    [scrollView setZoomScale:minimumZoomScale animated:NO];
    [self scrollViewDidEndZooming:self.scrollView withView:self.imageView atScale:minimumZoomScale];
}


//MARK: -
//MARK: UIViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
                                              initWithBarButtonSystemItem:UIBarButtonSystemItemAction
                                              target:self
                                              action:@selector(actionPressed)] autorelease];
}


//MARK: -
//MARK: UIScrollViewDelegate

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)view {
    return self.imageView;
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale {
    CGSize imageSize = self.imageView.image.size;
    self.imageView.frame = CGRectMake(0, 0, imageSize.width * scale, imageSize.height * scale);
    self.scrollView.contentSize = self.imageView.frame.size;
}


//MARK: -
//MARK: Button Actions

- (void)actionPressed {
    UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:nil
                                       delegate:self
                              cancelButtonTitle:LocalizedString(@"Cancel")
                         destructiveButtonTitle:nil
                              otherButtonTitles:LocalizedString(@"Save to Photo Library"),
                                                LocalizedString(@"Copy to clipboard"),
                                                LocalizedString(@"Email image"),
                                                nil];
	actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
	[actionSheet showInView:[[UIApplication sharedApplication] keyWindow]];    
}


//MARK: -
//MARK: UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
    switch (buttonIndex) {
        case 0:
            UIImageWriteToSavedPhotosAlbum(self.imageView.image, nil, nil, NULL);
            break;
        
        case 1:
        {
            NSString *uti = (NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, 
                                                                              (CFStringRef)file.content,
                                                                              NULL);            
            [[UIPasteboard generalPasteboard] setData:self.data forPasteboardType:uti];
            [uti release];
            break;
        }
        
        case 2:
        {
            MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
            picker.mailComposeDelegate = self;
            
            [picker setSubject:LocalizedString(@"An image from Pithos")];            
            [picker setMessageBody:LocalizedString(@"{Email image body}") isHTML:NO];
            [picker addAttachmentData:self.data mimeType:file.content fileName:file.name];
            
            [self presentModalViewController:picker animated:YES];
            [picker release];            
            break;
        }
    }
    
    [actionSheet release];
}


//MARK: -
//MARK: MFMailComposeViewControllerDelegate

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
	if (result == MFMailComposeResultFailed) {
        NSString *message = [NSString stringWithFormat:
                             LocalizedString(@"{Email operation failed}"),
                             [error userInfo]];
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:LocalizedString(@"Email image")
                                                        message:message
                                                       delegate:nil
											  cancelButtonTitle:nil
											  otherButtonTitles:LocalizedString(@"OK"), nil];
		[alert show];
		[alert release];
	}
    
	[self dismissModalViewControllerAnimated:YES];
}

@end